export default {
	namespaced:true,
	state(){
		return {
			carts:uni.getStorageSync('carts') || []
		}
	},
	getters:{
		// 获取商品数量
		goodsCount(state){
			return state.carts.length
		},
		// 商品是否全选
		allChecked(state){
			return state.carts.every(item=>item.goods_state)
		},
		// 获取结算商品的数量
		payCount(state){
			return state.carts.reduce((count,item)=>{
				if(item.goods_state){
					return count+=item.goods_number
				}
				return count
			},0)
		},
		// 获取结算商品的总价格
		payPrice(state){
			return state.carts.reduce((price,item)=>{
				if(item.goods_state){
					return price+=item.goods_number*item.goods_price
				}
				return price
			},0)
		}
	},
	mutations:{
		saveGoods(state,goods){
			// console.log(goods)
			// 查找出重复的商品
			const result = state.carts.find(item=>item.goods_id===goods.goods_id)
			if(result){
				result.goods_number+=1
			}else{
				state.carts.push(goods)
			}
			// 存储在本地
			this.commit('cart/saveToStorage')
		},
		// 商品状态更改
		toggleCheckBox(state,index){
			state.carts[index].goods_state=!state.carts[index].goods_state
			this.commit('cart/saveToStorage')
		},
		// 全选切换
		toggleAllChecked(state,allChecked){
			state.carts.forEach(item=>{
				item.goods_state=!allChecked
			})
		},
		// 商品的加减
		desNumber(state,index){
			if(state.carts[index].goods_number<=1){
				return uni.showToast({
					title:'商品仅剩1件',
					icon:'none'
				})
			}
			state.carts[index].goods_number-=1
			this.commit('cart/saveToStorage')
		},
		addNumber(state,index){
			state.carts[index].goods_number+=1
			this.commit('cart/saveToStorage')
		},
		// 本地存储
		saveToStorage(state){
			uni.setStorageSync('carts',state.carts)
		}
	}
}